package com.haojii.helloworld;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.haojii.jdo.utils.PMF;

public class ContactUtils {

	private static final Logger log = Logger.getLogger(ContactUtils.class.getName());

	public static List<Contact> list() {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query query = pm.newQuery(Contact.class);
		List<Contact> es = (List<Contact>) query.execute();
		List<Contact> result = (List<Contact>) pm.detachCopyAll(es);
		pm.close();
		return result;
	}

	public static Contact get(Long id) {
		Contact e = null, detached = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			e = pm.getObjectById(Contact.class, id);
			detached = pm.detachCopy(e);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			pm.close();
		}
		return detached;
	}

	public static boolean save(Contact Contact) {
		boolean result = true;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			pm.makePersistent(Contact);
		
		} catch (Exception ex) {
			result = false;
			ex.printStackTrace();
		} finally {
			pm.close();
		}
		return result;
	}

	public static boolean update(Contact Contact) {
		boolean result = true;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		try{
			Contact dest = pm.getObjectById(Contact.class, Contact.getId());
			if (dest != null) {
				pm.makePersistent(Contact);
			}
		} catch (Exception ex) {
			result = false;
			ex.printStackTrace();
		} finally {
			pm.close();
		}
		
		return result;
	}

	public static boolean delete(Contact Contact) {
		boolean result = true;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			Contact dest = pm.getObjectById(Contact.class, Contact.getId());
			if (dest != null) {
				pm.deletePersistent(Contact);
			}
		} catch (Exception ex) {
			result = false;
			ex.printStackTrace();
		} finally {
			pm.close();
		}
		return result;
	}
	
	public static boolean delete(Long id) {
		boolean result = true;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			Contact dest = pm.getObjectById(Contact.class, id);
			if (dest != null) {
				pm.deletePersistent(dest);
			}
		} catch (Exception ex) {
			result = false;
			ex.printStackTrace();
		} finally {
			pm.close();
		}
		return result;
	}

}
